package com.qisimanxiang.dalaran.zuul.filter;

import com.netflix.util.Pair;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.netflix.zuul.http.ServletInputStreamWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.POST_TYPE;

/**
 * @author wangmeng
 */
@Component
@Slf4j
public class CustomPostFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        try {
            RequestContext currentContext = RequestContext.getCurrentContext();
            if (currentContext.getResponse().getStatus() != 200) {
                return null;
            }
            InputStream responseDataStream = currentContext.getResponseDataStream();
            String body = StreamUtils.copyToString(responseDataStream, StandardCharsets.UTF_8);

            currentContext.setResponseDataStream(new ServletInputStreamWrapper(body.getBytes(StandardCharsets.UTF_8)));
            log.info("正常请求响应体:{}", body);
            currentContext.setResponseBody(body);
        } catch (IOException e) {
            log.info("处理响应体失败", e);
            throw new RuntimeException("处理响应体失败", e);
        }
        return null;
    }
}
